import time
import os
from collections import OrderedDict
from django.template import loader
from django.conf import settings

#1,加载环境变量
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mall.settings")

#2,初始化django环境
import django
django.setup()

#3,导入模型类
from goods.models import GoodsChannel
from contents.models import ContentCategory

def generate_static_index_html():
    """
    生成静态的主页html
    """

    print('%s:generate_static_index' % time.ctime())

    #1,定义所用分类字典
    categories = OrderedDict()

    #2,获取一级分类(37条数据分为11组)
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    #3,对一级分类进行遍历
    for channel in channels:
        # 获取group_id
        group_id = channel.group_id
        # 判断group_id 是否在存储容器,如果不在就初始化
        if group_id not in categories:
            categories[group_id] = {
                'channels': [],
                'sub_cats': []
            }

        #3,1取出一级分类
        one = channel.category

        # 为channels填充数据
        categories[group_id]['channels'].append({
            'id': one.id,
            'name': one.name,
            'url': channel.url
        })

        #3,2添加二级分类
        # 为sub_cats填充数据
        for two in one.goodscategory_set.all():
            # 初始化 容器
            two.sub_cats = []

            # 3.3遍历获取三级分类
            for three in two.goodscategory_set.all():
                two.sub_cats.append(three)

            # 组织数据
            categories[group_id]['sub_cats'].append(two)

    #4,广告和首页数据
    contents = {}
    content_categories = ContentCategory.objects.all()
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

    #5,拼接数据(分类,广告)
    context = {
        'categories': categories,
        'contents': contents
    }

    #6,获取模板
    template = loader.get_template('index.html')
    html_data = template.render(context)

    #将文件写入
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR,'index.html')
    with open(file_path,'w',encoding='utf-8') as f:
        f.write(html_data)

if __name__ == '__main__':
    generate_static_index_html()